import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;


public class DiskWriter implements Runnable {
	Queue<byte[]> list;
	ByteArrayOutputStream baos = new ByteArrayOutputStream();	
	byte[] line;
	StringBuffer sb = new StringBuffer();

	public DiskWriter() {
		list = new LinkedList<byte[]>();
		new Thread(this).start();
	}

	public void addToBuffer(StringBuffer appendMe) {
		try {
			sb.append(appendMe);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		System.out.println(" ONE DISKWRITER");
		try {
			FileChannel rwChannel = new RandomAccessFile("test", "rw").getChannel();
			ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, Integer.MAX_VALUE);

			//			File f = new File(System.currentTimeMillis() + "");
			//			RandomAccessFile raf = new RandomAccessFile(f, "rw");

			//			FileOutputStream fos = new FileOutputStream(f);
			//			DataOutputStream dos = new DataOutputStream(fos);


			while (true) {
				while (sb.length() == 0) {
					Thread.sleep(100);
				}
				synchronized (sb) {
					//dos.writeBytes();
					wrBuf.put(sb.toString().getBytes());				
					sb = new StringBuffer();

				}
				if (!wrBuf.hasRemaining()) {
					rwChannel.force(false);
				}
				//				synchronized (baos) {
				//					System.out.println("WRITING");
				//				raf.writeChars(baos.toString());				
				//				baos.reset();
				//				}


			}
		} catch (Exception e) {
			System.out.println(e);
		}


	}
}